package com.lookoutthebush.companyindex.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 校验工具类
 *
 * @author LookOutTheBush
 * @date 2021/9/14 6:49 下午
 */
@Slf4j
public class CheckUtil {

    public static boolean isEmpty(Number number) {
        return null == number || number.equals(0);
    }

    /**
     * 那个filed空就返回哪个filed
     *
     * @param obj 对象
     * @param fields 需要校验的field
     * @return str
     */
    public static String isEmpty(Object obj, String... fields) {
        Map<String, Object> map = getObjectToMap(obj);
        for (String field : fields) {
            if (isEmpty(map, field)) {
                return field;
            }
        }
        return "";
    }

    private static boolean isEmpty(Map<String, Object> map, String key) {
        return map.get(key) == null || ObjectUtils.isEmpty(map.get(key));
    }

    public static Map<String, Object> getObjectToMap(Object obj) {
        Map<String, Object> map = new LinkedHashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                log.info("object to map failed", e);
            }
            if (value == null) {
                value = "";
            }
            map.put(fieldName, value);
        }
        return map;
    }
}
